<template>
  <a-modal @cancel="close" title="拒绝工单" width="45vw" v-model:visible="visible" unmount-on-close>
    <div style="height: 320px">
      <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
        <page-form-row>
          <page-form-item field="refuseWorkReason" label="拒绝原因" required size="1">
            <a-textarea placeholder="请输入" :max-length="100" v-model="form.refuseWorkReason" auto-size />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" @click="handleBeforeOk" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup name="refuseModal">
  import { refuseWork } from '@/api/business/workorder'
  import { Message } from '@arco-design/web-vue'
  import { ref } from 'vue'
  // emit 事件
  const emit = defineEmits(['ok'])
  const visible = ref(false)
  const orderInfo = ref({})
  const form = ref({})
  const rules = {
    refuseWorkReason: [{ required: true, message: '请填写拒绝原因' }],
  }
  const open = (record) => {
    form.value = {
      id: record.id,
      status: record.status,
      refuseWorkReason: '',
    }
    visible.value = true
  }
  // 关闭
  const close = () => {
    visible.value = false
  }
  const formRef = ref()
  const okLoading = ref(false)
  const validateFn = () => {
    okLoading.value = true
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          okLoading.value = false
          console.log(error)
          reject()
        } else {
          resolve()
        }
      })
    })
  }
  const handleBeforeOk = (done) => {
    return new Promise((resolve, reject) => {
      validateFn().then(() => {
        refuseWork({ ...form.value })
          .then((res) => {
            console.log(res)
            Message.success(res.message)
            emit('ok')
            visible.value = false
            done()
            resolve()
          })
          .finally(() => {
            okLoading.value = false
          })
      })
    })
  }
  defineExpose({
    open,
  })
</script>
<style lang="less" scoped>
  :deep(.arco-row) {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  :deep(.arco-modal-body) {
    padding: 10px 80px !important;
  }
  :deep(.arco-col) {
    padding: 0 10px !important;
  }
</style>
